import axios from 'axios'
import request from '@/config/request'
import { getAnswerScoreable, generateEnglishQuestions, jywConvertToXkw } from '@/utils/question'
import { getAllSubjectApi, getSelfModuleSubjectApi, questionSplitApi } from '@/api/common'

// 获得已有作业科目列表
export const getStudentExamSubjectApi = (data) => {
  return new Promise((resolve) => {
    Promise.all([
      getAllSubjectApi({
        formatter: (subjects) => {
          return subjects.map((item) => {
            return item.value
          })
        }
      }),
      getSelfModuleSubjectApi()
    ]).then((res) => {
      const [subjectIdListData, moduleSubjectListData] = res
      const { data: subjectIdList } = subjectIdListData
      const { data: moduleSubjectList } = moduleSubjectListData
      // 获取已经开通的科目
      if (Array.isArray(moduleSubjectList) && moduleSubjectList.length > 0) {
        const selfSubjectList = moduleSubjectList.filter((i) => i.moduleId === '1')
        if (Array.isArray(subjectIdList) && selfSubjectList.length > 0) {
          const copySubjectIdList = JSON.parse(JSON.stringify(subjectIdList))
          const selfSubjectIds = selfSubjectList.map((i) => i.subject)
          subjectIdList.splice(0, subjectIdList.length)
          subjectIdList.push(...copySubjectIdList.filter((i) => selfSubjectIds.includes(i)))
        } else {
          subjectIdList.splice(0, subjectIdList.length)
        }
      } else {
        subjectIdList.splice(0, subjectIdList.length)
      }
      resolve(subjectIdListData)
    })
  })
}

// 获取学生作业列表
export const getStudentExamListApi = (data) => {
  return request.get('/app-api/exam/app/exam/examPage', data)
}

// 获取作业的详情
export const getStudentExamApi = (data) => {
  return request.get('/app-api/exam/app/exam/getExam', data)
}

// 获取问题
export const getQuestionsApi = (url, params = {}) => {
  const { subjectId, examType } = params

  return new Promise(async (resolve) => {
    switch (examType) {
      case 4:
        // 非习题作业
        {
          const { data: _data = {} } = await axios.get(url)
          let data = [] // 题目列表

          if (_data.questions) {
            data = _data.questions
          } else {
            data = _data
          }

          resolve(data)
        }
        break
      default:
        // 习题作业
        {
          const { data: _data = {} } = await axios.get(url)
          let data = [] // 题目列表

          // 分类并生成题目列表
          if (_data.questions) {
            if (subjectId == '66') {
              data = generateEnglishQuestions(_data) // 英语听说
            } else {
              data = _data.questions // 学科网、教辅题库、菁优网等题目
            }
          } else {
            data = _data // 学科网、教辅题库、菁优网等题目（兼容旧的）
          }

          try {
            // 遍历题目列表，如果不是学科网题目，将题目改为学科网的题目结构
            data = data.map((q) => {
              // 菁优网
              if (q.sourceType && q.sourceType === '3') {
                jywConvertToXkw(q)
              }

              return q
            })

            if (data) {
              // 题目解析
              const { data: questionSplitRes = [] } = await questionSplitApi(
                data.map((i) => {
                  return {
                    questionId: i.questionId,
                    stem: i.stem,
                    answer: i.answer,
                    explanation: i.explanation
                  }
                })
              )

              // 获取题型
              const { data: questionTypeDict } = await getQuestionTypeListApi({
                ids: data.map((item) => item.typeId).join(',')
              })

              resolve(
                data.map((q) => {
                  const { typeId } = q

                  const questionSplit = questionSplitRes.find((s) => s.questionId === q.questionId)
                  try {
                    q['stem'] = JSON.parse(q.stem)
                  } catch (error) {}
                  try {
                    q['answer'] = JSON.parse(q.answer)
                  } catch (error) {}
                  q['questionSplit'] = {
                    stem: JSON.parse(
                      questionSplit.stem.replace(
                        /<fieldset style=\\\"margin-top:0.1rem;font-size:0.26rem\\\">\\n /,
                        '<fieldset style=\\"margin-top:0.1rem;font-size:0.26rem\\">'
                      )
                    ),
                    answer: JSON.parse(questionSplit.answer),
                    explanation: JSON.parse(questionSplit.explanation)
                  }
                  const questionType = questionTypeDict.find((q) => q.id == typeId)
                  q['typeName'] = questionType && questionType.name ? questionType.name : '未知题型'
                  q.answerScoreable = getAnswerScoreable({
                    stem: q.questionSplit.stem,
                    answer: q.questionSplit.answer
                  })

                  return q
                })
              )
            } else {
              resolve(data)
            }
          } catch (error) {}
        }
        break
    }
  })
}

// 更新作业单个学生的自动提交时间
export const updateExamStudentEndtimeApi = (data) => {
  return request.post(`/app-api/exam/app/exam/updateExamStudentEndtime`, data)
}

// 提交学生作答
export const upExamQuestionAnswerApi = (data) => {
  return request.post(`/app-api/exam/app/exam/upExamQuestionAnswer`, data)
}

// 获得考试学生题目作答情况
export const getExamStudentQuestions = (data) => {
  return request.post(`/app-api/exam/app/exam/getExamStudentQuestions`, data)
}

// 提交完成作业，普通作业
export const upExamCompleteApi = (data) => {
  return request.post('/app-api/exam/app/exam/upExamComplete', data)
}

// 获取题型
export const getQuestionType = (data) => {
  return request.get('/app-api/question/App/type/get', data)
}

// 获取题型列表
export const getQuestionTypeListApi = (data) => {
  return request.get('/app-api/question/App/type/list', data)
}
